package com.xdty.fastInput;

import com.xdty.fastInput.utils.RobotUtil;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;


import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GlobalKeyListenerExample implements NativeKeyListener {

    private static final String CTRL = "ctrl";
    private FastInputApp fastInputApp;

    public GlobalKeyListenerExample(FastInputApp fastInputApp) {
        this.fastInputApp = fastInputApp;
        try {
            // 设置日志级别，避免不必要的日志输出
            Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
            logger.setLevel(Level.OFF);

            // 注册全局键盘监听器
            GlobalScreen.registerNativeHook();
            GlobalScreen.addNativeKeyListener(this);
        } catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());
        }
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent nativeEvent) {
        // 不处理
    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent nativeEvent) {
        // 摁下
        String pressedKey = NativeKeyEvent.getKeyText(nativeEvent.getKeyCode());
        if (CTRL.equalsIgnoreCase(pressedKey)){
            FastInputApp.ctrlIsActive = true;
            FastInputApp.keyIsActive = false;
            FastInputApp.pressedOtherKey = "";
        }

        if (!CTRL.equalsIgnoreCase(pressedKey)){
            FastInputApp.pressedOtherKey = pressedKey.toLowerCase();
            FastInputApp.keyIsActive = true;
        }

        if (FastInputApp.ctrlIsActive && FastInputApp.keyIsActive){
            String mapKey = CTRL+"+"+FastInputApp.pressedOtherKey;
            Optional<Map<String, String>> first = fastInputApp.getIsAction().stream().filter(map -> map.containsKey(mapKey)).findFirst();
            if (first.isPresent()){
                String content = first.get().get(mapKey);
                RobotUtil.autoInput(content);
            }
            FastInputApp.ctrlIsActive = false;
            FastInputApp.keyIsActive = false;
        }
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent nativeEvent) {
        // 松开
        //System.out.println("Key Released: " + NativeKeyEvent.getKeyText(nativeEvent.getKeyCode()));
    }
}
